using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace DSEngine.Common
{
    public class SchedulerManager
    {
        private SchedulerManager()
        {
        }
        private static SchedulerManager instance;
        public static SchedulerManager Instance
        {
            get
            {
                if (instance == null)
                    instance = new SchedulerManager();
                return instance;
            }
        }
        List<Scheduler> schedulerList = new List<Scheduler>();
        List<Scheduler> tmpSchedulerList = new List<Scheduler>();
        public void AddScheduler(Scheduler scheduler)
        {
            tmpSchedulerList.Add(scheduler);
        }
        public void RemoveScheduler(Scheduler scheduler)
        {
            schedulerList.Remove(scheduler);
        }
        public bool IsPuase { get; set; }
        public void Puase()
        {
            this.IsPuase = true;
        }
        public void Resume()
        {
            this.IsPuase = false;
        }
        public void Update(GameTime gameTime)
        {
            foreach (var item in tmpSchedulerList)
            {
                schedulerList.Add(item);
            }
            tmpSchedulerList.Clear();
            List<Scheduler> s2remove = new List<Scheduler>();
            if (IsPuase)
            {
                return;
            }
            foreach (var item in schedulerList)
            {
                if (item.IsPause)
                {
                    continue;
                }
                item.CurrentDuring += (float)gameTime.ElapsedGameTime.TotalMilliseconds;
                if (item.CurrentDuring >= item.During)
                {
                    item.Callback(item,item.Param);
                    if (item.Loop)
                    {
                        item.CurrentDuring = 0;
                    }
                    else
                    {
                        s2remove.Add(item);
                        continue;
                    }
                }
            }
            foreach (var item in s2remove)
            {
                schedulerList.Remove(item);
            }
        }
    }
}
